﻿

using LeaderCCSLaserUI.Data.Extensions;
using LeaderCCSLaserUI.Models;
using netDxf.Tables;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Dialogs
{
    public class PartNumDialogViewModel : DialogViewModel
    {
        #region 变量
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private Param? systemParam;
        #endregion
        #region 属性绑定
        private string currentPartNum;
        public string CurrentPartNum
        {
            get { return currentPartNum; }
            set { SetProperty(ref currentPartNum, value); }
        }
        private ObservableCollection<MyPartNum> partNumbList;
        public ObservableCollection<MyPartNum> PartNumbList
        {
            get { return partNumbList; }
            set { SetProperty(ref partNumbList, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand addCommand;
        public DelegateCommand AddCommand =>
            addCommand ?? (addCommand = new DelegateCommand(ExecuteAddCommand));
        private DelegateCommand<MyPartNum> deleteCommand;
        public DelegateCommand<MyPartNum> DeleteCommand =>
            deleteCommand ?? (deleteCommand = new DelegateCommand<MyPartNum>(ExecuteDeleteCommand));
        private DelegateCommand<MyPartNum> selectCommand;
        public DelegateCommand<MyPartNum> SelectCommand =>
            selectCommand ?? (selectCommand = new DelegateCommand<MyPartNum>(ExecuteSelectCommand));

        void ExecuteSelectCommand(MyPartNum partNum)
        {
            if (partNum != null)
            {
                if (partNum.Name != CurrentPartNum)
                {
                    
                    if (MessageBox.Show($"确认切换为\"{partNum.Name}\"料号吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                    {
                        systemParam.PartIndex = partNum.Id - 1;
                        CurrentPartNum = systemParam.PartList[systemParam.PartIndex];
                        SavedParam();
                        aggregator.SendMessage("ReloadParam", "Run");
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteDeleteCommand(MyPartNum partNum)
        {
            if (partNum != null)
            {
                if (partNum.Name != CurrentPartNum)
                {                    
                    if (MessageBox.Show($"确定删除料号\"{partNum.Name}\"吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                    {                       
                        try
                        {
                            //删除文件夹
                            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, partNum.Name));
                            di.Delete(true);
                            systemParam.PartList.Remove(partNum.Name);
                            PartNumbList.Clear();
                            for (int i = 0; i < systemParam.PartList.Count; i++)
                            {
                                if (systemParam.PartList[i] == CurrentPartNum)
                                {
                                    systemParam.PartIndex = i;
                                }
                                PartNumbList.Add(new MyPartNum
                                {
                                    Id = i + 1,
                                    Name = systemParam.PartList[i]
                                });
                            }
                            SavedParam();
                            aggregator.SendMessage("ReloadParam", "Run");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("不能删除当前料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("未选择任何料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteAddCommand()
        {
            dialogService.ShowDialog("AddNewPartNumDialog",arg =>
            {
                if (arg.Result == ButtonResult.Yes)
                {
                    var newpartName = arg.Parameters.GetValue<string>("NewPartNumName");
                    if (newpartName != string.Empty)
                    {
                        var _part = systemParam.PartList.FirstOrDefault(p => p == newpartName);
                        if (_part == null)
                        {
                            try
                            {
                                //创建新文件夹
                                Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, newpartName));

                                //复制数据                                        
                                FileHelper.DirectoryCopy(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, CurrentPartNum), System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, newpartName), true);

                                systemParam.PartList.Add(newpartName);
                                PartNumbList.Clear();
                                for (int i = 0; i < systemParam.PartList.Count; i++)
                                {
                                    PartNumbList.Add(new MyPartNum
                                    {
                                        Id = i + 1,
                                        Name = systemParam.PartList[i]
                                    });
                                }
                                SavedParam();
                                aggregator.SendMessage("ReloadParam", "Run");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show($"料号\"{newpartName}\"已存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("料号名不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            LoadParam();
            try
            {
                CurrentPartNum = systemParam.PartList[systemParam.PartIndex];
                for (int i = 0; i < systemParam.PartList.Count; i++)
                {
                    PartNumbList.Add(new MyPartNum
                    {
                        Id = i + 1,
                        Name = systemParam.PartList[i]
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
           
        }
        #endregion
        public PartNumDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            PartNumbList = new ObservableCollection<MyPartNum>();
        }
        #region 功能函数
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                systemParam = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        void SavedParam()
        {
            try
            {
                string jsonString = JsonConvert.SerializeObject(systemParam, Formatting.Indented);
                File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"), jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

        }
        #endregion
    }
    public class MyPartNum
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
